#include "shippool.h"
#include "dispatcher.h"

ShipPool::ShipPool(QObject *parent) : QObject(parent)
{
    fillShip();
}

void ShipPool::passShip(const QString front_ship)
{
    for(auto& ship : m_ship_pool){
        if(ship->getId() == front_ship){
            ship->setIsPass(true);
        }
    }
}

void ShipPool::fillShip()
{
    for(int i =0; i < 10; ++i){
        auto sp = std::make_shared<Ship>("ship_" + QString::number(i));
        connect(sp.get(), &Ship::loadReady, this, &ShipPool::onShipTransportAway);
        connect(sp.get(), &Ship::loadReady, Dispatcher::getInstance(), &Dispatcher::onShipTransportAway);
        sp->start();
        m_ship_pool.push_back(sp);
    }
    updateShipList(getNewShipList(m_ship_pool));
}

QStringList ShipPool::getNewShipList(std::list<std::shared_ptr<Ship> > &ship_pool)
{
    QStringList li;
    for(const auto& sp : ship_pool){
        QString msg =  sp->getId();
        if(!sp->getCargoId().isEmpty()){
            msg.append("," + sp->getCargoId());
        }
        li << msg;
    }
    return li;
}

void ShipPool::onShipTransportAway(const Ship* ship)
{
    for(auto& item : m_ship_pool){
        if(item->getId() == ship->getId()){
            m_loaded_ship_pool.push_back(item);
            m_ship_pool.remove(item);
        }
    }

    updateShipList(getNewShipList(m_ship_pool));
    updateLoadedShipList(getNewShipList(m_loaded_ship_pool));
}
